import auth from '@/plugins/auth'
import router, { constantRoutes, dynamicRoutes, allPagesRoutes } from '@/router'
import { getRouters } from '@/api/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'
import useUserStore from '@/store/modules/user'
import { cloneDeep } from 'lodash-es'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

const usePermissionStore = defineStore(
  'permission',
  {
    state: () => ({
      routes: [],
      addRoutes: [],
      defaultRoutes: [],
      topbarRouters: [],
      sidebarRouters: []
    }),
    actions: {
      setRoutes(routes) {
        this.addRoutes = routes
        this.routes = constantRoutes.concat(routes)
      },
      setDefaultRoutes(routes) {
        this.defaultRoutes = constantRoutes.concat(routes)
      },
      setTopbarRoutes(routes) {
        this.topbarRouters = routes
      },
      setSidebarRouters(routes) {
        this.sidebarRouters = routes
      },
      generateRoutes() {
        return new Promise(resolve => {
          const userStore = useUserStore()
          const roles = userStore.getPermissions()
          console.log('获取用户菜单权限', roles)
          const accessedRoutes = filterAsyncRouter(allPagesRoutes, roles)
          console.log('accessedRoutes', accessedRoutes)
          this.setRoutes(accessedRoutes)
          // 设置侧边栏路由
          this.setSidebarRouters(constantRoutes.concat(accessedRoutes))
          // 设置顶部路由
          this.setTopbarRoutes(constantRoutes.concat(accessedRoutes))
          resolve(accessedRoutes)
        })
      }
    }
  })

function filterAsyncRouter(asyncRouterMap, roles) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.id && roles.some(roleId => roleId === route.id)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

export default usePermissionStore
